package com.watson.nettydemo.demo07;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.net.SocketAddress;

/**
 * SimpleChannelInboundHandler 与 ChannelInboundHandlerAdapter 的区别，，SimpleChannelInboundHandler会将消息自动释放
 *
 * @author: llun
 * @date: 2022/3/11 14:54
 * @version: 1.0
 */
public class WebSocketServerHandler extends ChannelInboundHandlerAdapter {
    EventExecutor executor;
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 需求 将发过来的消息发回去
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        channels.forEach(item -> {
            if (item != channel) {
                item.writeAndFlush(channel.remoteAddress() + ":" + msg + "\n");
            } else {
                item.writeAndFlush("me" + msg + "\n");
            }
        });
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(ctx.channel().remoteAddress() + "=====上线");
        channels.writeAndFlush(ctx.channel().remoteAddress() + "=====上线");
        channels.add(channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // group中存放的都是Active状态的Channel
        // 一旦某channel的状态不再是Active,
        // group会自动将其从集合中踢出，所以，下面的语句不用写
        //remove()方法的应用场景是，将一个Active状态的channeL移出
        // group.remove( channel);*/
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        System.out.println(socketAddress + "=====下线");
        channels.writeAndFlush(socketAddress + "===下线，现在在线人数：" + channels.size());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        cause.printStackTrace();
        ctx.close();
    }
}
